#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys

from queue import Queue
from flask import Flask, jsonify, send_file, request

from basic.config import GlobalCfg
from basic.workspace import Workspace
from basic.log import Log
from basic.data.database import DBService
from modules.master import ModuleMaster
from modules.admin import VisitRecordTable


# 1.init
if len(sys.argv) < 2:
    print('缺少配置文件')
    exit(0)

GlobalCfg.init(sys.argv[1])
workspace = Workspace(None, 'project')
log = Log(workspace.path)

database = DBService()
modules_master = ModuleMaster()
website = Flask(__name__)

vrt = VisitRecordTable(workspace)


# 2. prepare routes
@website.route('/')
def website_homepage():
    vrt.insert(request.remote_addr, "/")
    return send_file('templates\\homepage.html')


@website.route('/devkit_admin')
def website_admin():
    return send_file('templates\\admin.html')


@website.errorhandler(404)
def error_404(error):
    return send_file('templates\\404.html'), 404


@website.route('/advertising_for_rent')
def advertising_for_rent():
    return send_file('templates\\advertising_for_rent.html')


modules_gate = []
for m in modules_master.website_modules:
    for r in m.routes:
        if r.desc is not None:
            log.log(f'入口路由{r.name}  {r.url}  {str(r.methods)}')
            modules_gate.append({"url": r.url, "name": r.name, "desc": r.desc})
        website.add_url_rule(r.url, endpoint=r.name, view_func=r.hook, methods=r.methods)
        log.log(f'添加路由{r.name}  {r.url}  {str(r.methods)}')


@website.route('/get_website_list_tools')
def get_website_list_tools():
    return jsonify(modules_gate)


@website.route('/website_list_tools')
def website_list_tools():
    return send_file('templates\\tools_list.html')


# run
log.log(f'开始运行。')
# TODO database.run()
modules_master.power_on()
website.run(GlobalCfg.web_ip, GlobalCfg.web_port)


